<template>
    <div class="app-container">
      <el-row :gutter="20" class="header">
        <el-col :span="7">
          <el-input 
            placeholder="请输入汇报内容关键词..." 
            v-model="queryForm.query" 
            clearable
            @keyup.enter="initReportList"
          ></el-input>
        </el-col>
        <!-- <el-col :span="5">
          <el-select 
            v-model="queryForm.query2" 
            placeholder="选择月份" 
            clearable
          >
            <el-option
              v-for="item in monthOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col> -->
        <el-button type="primary" :icon="Search" @click="initReportList">搜索</el-button>
        <el-button 
          type="success" 
          :icon="DocumentAdd" 
          @click="handleAdd"
        >
          新增汇报
        </el-button>
      </el-row>
  
      <el-table 
        :data="tableData" 
        stripe 
        style="width: 100%" 
        v-loading="loading"
      >
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="username" label="汇报人" width="120" align="center" />
        <el-table-column prop="bumen" label="部门" width="120" align="center" />
        <el-table-column prop="gangwei" label="岗位" width="120" align="center" />
        <el-table-column prop="addtime" label="汇报时间" width="180" align="center">
          <template #default="{row}">
            {{ formatDate(row.addtime) }}
          </template>
        </el-table-column>
        <el-table-column prop="scoreMonth" label="月份" width="100" align="center">
          <template #default="{row}">
            {{ row.scoreMonth }}月
          </template>
        </el-table-column>
        <el-table-column prop="reportContent" label="汇报内容" show-overflow-tooltip />
        <el-table-column prop="score" label="评分" width="120" align="center">
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template #default="{row}">
            <el-button 
              type="primary" 
              size="small" 
              :icon="Edit" 
              @click="handleEdit(row)"
            />
            <el-popconfirm 
              title="您确定要删除这条记录吗？" 
              @confirm="handleDelete(row.id)"
            >
              <template #reference>
                <el-button 
                  type="danger" 
                  size="small" 
                  :icon="Delete"
                />
              </template>
            </el-popconfirm>
        
            <el-button 
              type="warning" 
              size="small" 
              :icon="EditPen" 
              @click="handleScore(row)"
            >
              评分
            </el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <el-pagination
        v-model:currentPage="queryForm.pageNum"
        v-model:page-size="queryForm.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
  
      <!-- 新增/编辑对话框 -->
      <el-dialog 
        v-model="dialogVisible" 
        :title="dialogTitle" 
        width="600px"
        @closed="resetForm"
      >
        <el-form 
          :model="formData" 
          :rules="rules" 
          ref="formRef" 
          label-width="100px"
        >
          <el-form-item label="汇报内容" prop="reportContent">
            <el-input
              v-model="formData.reportContent"
              type="textarea"
              :rows="8"
              placeholder="请输入项目进度汇报内容"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitForm"
            :loading="submitting"
          >
            确定
          </el-button>
        </template>
      </el-dialog>
  
     <!-- 评分对话框 -->
     <el-dialog 
        v-model="scoreDialogVisible" 
        title="评分" 
        width="500px"
      >
        <el-form 
          :model="scoreForm" 
          ref="scoreFormRef" 
          label-width="100px"
        >
          <el-form-item label="评分(0-20)">
            <el-input-number 
              v-model="scoreForm.score" 
              :min="0" 
              :max="20" 
              controls-position="right"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="scoreDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="submitScore"
            :loading="scoring"
          >
            确定
          </el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, computed } from 'vue';
  import { Search, Delete, DocumentAdd, Edit, EditPen } from '@element-plus/icons-vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import requestUtil from "@/util/request";
  import store from '@/store'


  // 表格数据
  const tableData = ref([]);
  const loading = ref(false);
  const total = ref(0);
  
  // 查询参数
  const queryForm = reactive({
    query: '',
    query2: null,
    pageNum: 1,
    pageSize: 10
  });
  
  // 对话框相关
  const dialogVisible = ref(false);
  const dialogTitle = ref('');
  const formRef = ref();
  const submitting = ref(false);
  
  // 评分对话框相关
  const scoreDialogVisible = ref(false);
  const scoreFormRef = ref();
  const scoring = ref(false);
  const currentScoreId = ref(null);
  
  // 表单数据
  const formData = reactive({
    id: undefined,
    userid: null,
    username: '',
    bumenid: null,
    gangweiid: null,
    reportContent: '',
    score: 0,
    query2: new Date().getMonth() + 1
  });
  
  // 评分表单
  const scoreForm = reactive({
    score: 0
  });
  
  // 评分颜色
  const scoreColors = ['#99A9BF', '#F7BA2A', '#FF9900']
  
  // 月份选项
  const monthOptions = ref([
    { value: 1, label: '1月' },
    { value: 2, label: '2月' },
    { value: 3, label: '3月' },
    { value: 4, label: '4月' },
    { value: 5, label: '5月' },
    { value: 6, label: '6月' },
    { value: 7, label: '7月' },
    { value: 8, label: '8月' },
    { value: 9, label: '9月' },
    { value: 10, label: '10月' },
    { value: 11, label: '11月' },
    { value: 12, label: '12月' }
  ]);
  
  // 表单验证规则
  const rules = {
    query2: [
      { required: true, message: '请选择月份', trigger: 'change' }
    ],
    reportContent: [
      { required: true, message: '请输入汇报内容', trigger: 'blur' },
      { min: 10, message: '汇报内容至少10个字符', trigger: 'blur' }
    ]
  };
  
  // 当前用户信息
  const currentUser = computed(() => store.getters.GET_USERINFO || {});

  
  // 初始化汇报列表
  const initReportList = async () => {
    try {
      loading.value = true;
      
      
      const currentUser = ref(store.getters.GET_USERINFO);
      if (!currentUser.value.roles || !currentUser.value.roles.includes('超级管理员')) {
        queryForm.query3 = currentUser.value.username;
      }
      const res = await requestUtil.post("sys/projectProgress/list", queryForm);
      tableData.value = res.data.list || [];
      total.value = res.data.total || 0;
    } catch (error) {
      ElMessage.error('获取数据失败: ' + (error.response?.data?.msg || error.message));
    } finally {
      loading.value = false;
    }
  };
  
  // 分页大小变化
  const handleSizeChange = (size) => {
    queryForm.pageSize = size;
    queryForm.pageNum = 1;
    initReportList();
  };
  
  // 当前页变化
  const handleCurrentChange = (page) => {
    queryForm.pageNum = page;
    initReportList();
  };
  
  // 新增汇报
  const handleAdd = async () => {
    // 检查本月是否已提交
    try {      
      dialogTitle.value = '新增进度汇报';
      formData.id = undefined;
      formData.userid = currentUser.value.id;
      formData.username = currentUser.value.username;
      formData.bumenid = currentUser.value.bumenid;
      formData.gangweiid = currentUser.value.gangweiid;
      formData.reportContent = '';
      formData.score = 0;
      formData.query2 = new Date().getMonth() + 1;
      dialogVisible.value = true;
    } catch (error) {
      ElMessage.error('检查提交状态失败: ' + error.message);
    }
  };
  
  // 编辑汇报
  const handleEdit = (row) => {
    dialogTitle.value = '编辑进度汇报';
    Object.assign(formData, row);
    dialogVisible.value = true;
  };
  
  // 提交表单
  const submitForm = async () => {
    try {
      await formRef.value.validate();
      submitting.value = true;
      
      //获取用户id
      const currentUser = ref(store.getters.GET_USERINFO);

      formData.username = currentUser.value.username;
      formData.userId = currentUser.value.id;
      formData.bumenid = currentUser.value.bumenid;
      formData.bumen = currentUser.value.bumen;
      formData.gangwei = currentUser.value.gangwei;
      formData.gangweiid = currentUser.value.gangweiid;
      const api = "sys/projectProgress/save";
      const res = await requestUtil.post(api, formData);
      
      if (res.data.code === 200) {
        ElMessage.success(res.data.msg || '操作成功');
        dialogVisible.value = false;
        initReportList();
      } else {
        ElMessage.error(res.data.msg || '操作失败');
      }
    } catch (error) {
      console.error(error);
    } finally {
      submitting.value = false;
    }
  };
  
  // 删除汇报
  const handleDelete = async (id) => {
    try {
      await ElMessageBox.confirm('确定要删除该进度汇报吗?', '提示', {
        type: 'warning'
      });
      
      const res = await requestUtil.post("sys/projectProgress/delete", [id]);
      if (res.data.code === 200) {
        ElMessage.success('删除成功');
        initReportList();
      } else {
        ElMessage.error(res.data.msg || '删除失败');
      }
    } catch (error) {
      console.error(error);
    }
  };
  
  // 评分操作
  const handleScore = (row) => {
    
  if (!currentUser.value.roles || !currentUser.value.roles.includes('超级管理员')) {
    ElMessage.error('您没有评分权限');
    return;
  }
    currentScoreId.value = row.id;
    scoreForm.score = row.score;
    scoreDialogVisible.value = true;
  };
  
  // 提交评分
  const submitScore = async () => {
    try {
      scoring.value = true;
      const res = await requestUtil.post("sys/projectProgress/save", {
        id: currentScoreId.value,
        score: scoreForm.score
      });
      
      if (res.data.code === 200) {
        ElMessage.success('评分成功');
        scoreDialogVisible.value = false;
        initReportList();
      } else {
        ElMessage.error(res.data.msg || '评分失败');
      }
    } catch (error) {
      console.error(error);
    } finally {
      scoring.value = false;
    }
  };
  
  // 重置表单
  const resetForm = () => {
    formRef.value?.resetFields();
    formData.id = undefined;
    Object.assign(formData, {
      reportContent: '',
      score: 0,
      query2: new Date().getMonth() + 1
    });
  };
  
  // 格式化日期
  const formatDate = (dateStr) => {
    if (!dateStr) return '';
    const date = new Date(dateStr);
    return date.toLocaleString();
  };
  
  // 初始化加载数据
  onMounted(() => {
    initReportList();
  });
  </script>
  
  <style lang="scss" scoped>
  .app-container {
    padding: 20px;
    height: calc(100vh - 40px);
    display: flex;
    flex-direction: column;
  }
 /* 新增这部分样式 */
 .header {
    flex-shrink: 0; // 防止头部被压缩
    margin-bottom: 20px;
  }
  
  .el-pagination {
    margin-top: 20px;
    justify-content: flex-end;
  }
  
  .el-button + .el-button {
    margin-left: 8px;
  }
  
  
/* 在当前组件的style中 */
::v-deep th.el-table__cell {
  color: #333; /* 改为深黑色 */
  background-color: #fff; /* 改为白色背景 */
  
  /* 如果需要更醒目的样式 */
  /* 
  background-color: #409eff !important;
  color: white !important;
  */
}
  
  </style>